<template>
  <VPage class="app-container">
    <VTable v-if="isRefresh" ref="tableRef" v-bind="tableOptins">
      <template #form="{ form }">
        <VGroup>
          <el-select class="selectClass" v-model="form.orderRange.type" placeholder="">
            <el-option v-for="item in orderOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <multiInput class="w-50" v-model="form.orderRange.value" placeholder="请输入"></multiInput>
        </VGroup>
        <multiInput class="w-50" v-model="form.sku" placeholder="SKU/自定义SKU"></multiInput>
        <select-personnel v-model="form.shelve_user_id" placeholder="上架人"></select-personnel>
        <SelectWarehouse class="selectClass" v-model="form.warehouse_id" placeholder="仓库" :multiple="true">
        </SelectWarehouse>
        <el-select class="selectClass" v-model="form.urgent_status" placeholder="是否加急" clearable>
          <el-option v-for="item in options['stockin.shelveOrder']?.[0].urgentStatus" :key="item.value"
            :label="item.label" :value="item.value"></el-option>
        </el-select>
        <el-select class="selectClass" v-model="form.shelve_status" placeholder="上架状态" clearable>
          <el-option v-for="item in options['stockin.shelveOrder']?.[0].detailShelveStatus" :key="item.value"
            :label="item.label" :value="item.value"></el-option>
        </el-select>
        <template v-if="activeName == 0">
          <el-select class="selectClass" v-model="form.type" placeholder="入库类型" clearable>
            <el-option v-for="item in options['stockin.shelveOrder']?.[0].orderShelveType" :key="item.value"
              :label="item.label" :value="item.value"></el-option>
          </el-select>
          <el-select v-model="form.order_status" placeholder="单据状态">
            <el-option v-for="item in options['stockin.shelveOrder']?.[0].detailStatus" :key="item.value"
              :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </template>
        <VGroup>
          <el-select class="selectClass" v-model="form.timeRange.type" style="max-width: 150px">
            <el-option v-for="item in timeOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <el-date-picker v-model="form.timeRange.value" type="daterange" range-separator="至" start-placeholder="开始时间"
            end-placeholder="结束时间" value-format="YYYY-MM-DD HH:mm:ss" :default-time="defaultTime()" style="max-width: 300px" />
        </VGroup>
      </template>
      <template #toolbar_btns>
        <div class="w-full ">
          <el-tabs v-model="activeName" class="pl-4 pr-4" @tab-change="handleChange">
            <el-tab-pane :label="item.label" :name="item.name" v-for="(item, index) in tabList"
              :key="index"></el-tab-pane>
          </el-tabs>
        </div>
        <el-button v-if="activeName == 1" type="primary" @click="handleShelve()">批量上架</el-button>
        <el-button class="ml-auto" @click="handleExport()"><svg-icon icon-class="import" />导出</el-button>
      </template>
    </VTable>
    <derived-center ref="DerivedCenterRef"></derived-center>
  </VPage>
</template>
<script setup name="StorageShelve-order" lang="jsx">
import { ElMessage } from 'element-plus'
import { nextTick, ref, reactive, toRefs } from 'vue'
import { getEnums } from '@/api/public'
import { queryListOrder, getOrder, createShelveOrder } from './api'
import { getWareData } from '@/api/public'
import multiInput from '@/components/multiInput';
import VImage from '@/components/Image/index.vue'
import SelectWarehouse from '@/components/SelectWarehouse'

const timeOption = [
  { label: "创建时间", value: "create_time" },
  { label: "上架时间", value: "shelve_time" },
]

const orderOption = [
  { label: "上架单号", value: "shelve_order_no" },
  { label: "相关单号", value: "order_no" },
]

const tabList = [
  {
    label: '入库上架',
    name: 0
  },
  {
    label: '入库上架明细',
    name: 1
  },
]

const tableRef = ref()
const tableOptins = reactive({
  rowConfig: { height: '60' },
  showHeaderOverflow: false,
  showOverflow: false,
  formConfig: {
    data: {
      orderRange: { type: 'shelve_order_no', value: [], range: false },
      timeRange: { type: 'create_time', value: [], range: true },
    }
  },
  columns: [
  ],
  proxyConfig: {
    seq: true,
    props: {
      result: 'data',
      total: 'total',
    },
    ajax: {
      query: async ({ page, form }) => {
        const requestFun = activeName.value == 0 ? queryListOrder : getOrder
        const res = await requestFun({ ...form, ...page })
        return new Promise(function (resolve) {
          resolve({
            data: res.data,
            total: res.total
          })
        })
      }
    }
  }
})

const initColumns = (type) => {
  if (type == 0) {
    tableOptins.columns = [
      {
        type: "seq", title: '序号', width: 80
      },
      {
        field: 'shelve_order_no', title: '上架单号', width: 200, slots: {
          default: ({ row }) => {
            return <div class="base-text-color cursor-pointer" onClick={() => showOrderDetail(row.shelve_order_no)}> {row.shelve_order_no} </div>
          }
        }
      },
      {
        field: 'order_no', title: '相关单号', width: 200
      },
      {
        field: 'warehouse_name', title: '收货仓', width: 190
      },
      {
        field: 'urgent_status_cn', title: '是否加急', width: 120
      },
      {
        field: 'shelve_status_cn', title: '上架状态', width: 120
      },
      {
        field: 'order_status_cn', title: '单据状态', width: 120
      },
      {
        field: 'create_user', title: '创建人', width: 160
      },
      {
        field: 'create_time', title: '创建时间', width: 180
      },
      {
        field: 'shelve_user', title: '上架人', width: 160
      },
      {
        field: 'shelve_time', title: '上架时间', width: 180
      },
      {
        field: 'platform_order_no', title: '平台单号', width: 200
      },
      {
        field: 'type_cn', title: '入库类型', width: 120
      }
    ]
  } else if (type == 1) {
    tableOptins.columns = [
      { type: 'checkbox', width: 50, fixed: 'left' },
      { type: 'seq', title: '序号', width: "80" },
      {
        field: 'inventory_count_order_no', title: '自定义/SKU', width: 200, slots: {
          default: ({ row }) => {
            return <div>
              <div>SKU: {row.sku}</div>
              <div>自定义SKU: {row.custom_sku}</div>
            </div>
          }
        }
      },
      {
        field: 'location_code', title: '产品名称', width: 200, slots: {
          default: ({ row }) => {
            return <div class="flex flex-col">
              <el-tooltip class="item" effect="dark" content={row.sku_cn_title} placement="top">
                <div class="overflow-line2 text-[#333333]">{row.sku_cn_title}</div>
              </el-tooltip>
              <el-tooltip class="item" effect="dark" content={row.sku_en_title} placement="top">
                <div class="overflow-line2 text-[#333333]">{row.sku_en_title}</div>
              </el-tooltip>
            </div >
          }
        }
      },
      {
        field: 'type_cn', title: '图片', width: 120, slots: {
          default: ({ row }) => {
            return <div> {row.image.map(i => {
              return <VImage src={i} width={60} height={60}></VImage>
            })
            } </div>
          }
        }
      },
      {
        field: 'num', title: '申请上架数量', width: 120
      },
      {
        field: 'ready_shelve_num', title: '待上架数量', width: 120
      },
      {
        field: 'recommend_area_name', title: '推荐区域', width: 120
      },
      {
        field: 'recommend_location_code', title: '推荐货位', width: 120
      },
      {
        field: 'shelve_location_code', title: '上架货位', width: 120, 
        slots: {
          default: ({ row }) => {
            return <div>{row.shelve_status == 2 ? <div>{row.shelve_location_code}</div> :<el-input v-model={row.shelve_location_code} placeholder="上架货位"></el-input>}</div>
          }
        }
      },
      {
        field: 'wait_shelve_num', title: '上架数量', width: 120,
         slots: {
          default: ({ row }) => {
            return <div>{row.shelve_status == 2 ? <div>{row.wait_shelve_num}</div> :<el-input v-model={row.wait_shelve_num} placeholder="上架数量"></el-input>}</div>
          }
        }
      },
      {
        field: 'shelve_num', title: '已上架数量', width: 120
      },
      {
        field: 'shelve_user', title: '上架人', width: 160
      },
      {
        field: 'shelve_time', title: '上架时间', width: 180
      },
      {
        field: 'remark', title: '备注', width: 120
      },
      {
        title: '操作', width: "100", fixed: "right", slots: {
          default: ({ row }) => {
            return <div class="table-option">
              <div>
                {row.shelve_status != 2 && <el-button type="primary" link onClick={() => handleShelve(row)}>上架</el-button>}
              </div>
            </div >
          }
        }
      }
    ]
  }
}
initColumns(0)

const query = () => {
  tableRef.value.query()
}

const data = reactive({
  options: [],
  wareDataList: [],
  activeName: 0,
  isRefresh: true
})
const { options, wareDataList, activeName, isRefresh } = toRefs(data)

// 获取枚举类
const fetchOption = async () => {
  getEnums({
    version: "v1", "name": [
      "stockin.shelveOrder"
    ]
  }).then(res => {
    options.value = res.data
  })
}
provide('options', options)
fetchOption()

// 获取仓库
const getWareDataList = async () => {
  try {
    const res = await getWareData()
    wareDataList.value = res.data
  } catch (e) {
    throw Error(e)
  }
}
provide('wareDataList', wareDataList)
getWareDataList()

const handleChange = (val) => {
  if(activeName.value == 0){
    tableOptins.formConfig.data.orderRange = { type: 'shelve_order_no', value: '' }
  }
  initColumns(activeName.value)
  isRefresh.value = false
  nextTick(() => {
    isRefresh.value = true
  })
}

//获取已选中的行
const getSelectRow = () => {
  return tableRef?.value.$table.getCheckboxRecords()
}

const handleShelve = async (row) => {
  const records = getSelectRow()
  if (!row) {
    if (records.length == 0) return ElMessage.error('至少勾选一个')
  }
  const item = row ? [row] : records
  const product_ids = item.map(i => {
    return {
      id: i.id,
      num: i.wait_shelve_num,
      location_code: i.shelve_location_code
    }
  })
  try {
    const res = await createShelveOrder({
      data: product_ids
    })
    ElMessage.success(res.message)
    query()
  } catch (e) {
    throw Error(e)
  }
}

const DerivedCenterRef = ref()
const handleExport = (val) => {
  let condition = tableRef.value.getQueryForm()
  DerivedCenterRef.value.open({
    id: 60,
    tag_name: 'wms',
    condition
  })
}

const showOrderDetail = (shelve_order_no) => {
  tableOptins.formConfig.data.orderRange = { type: 'shelve_order_no', value: shelve_order_no }
  // tableRef.value.setForm({
  //   shelve_order_no
  // })
  activeName.value = 1
  handleChange()
}
</script>
<style scoped>
:deep(.el-tabs__nav-wrap::after) {
  height: 1px;
}
</style>